package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.LeyouItemServiceApplication;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;



import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service

public class GoodService {

    private static Logger logger = LoggerFactory.getLogger(LeyouItemServiceApplication.class);

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 根据条件搜索分页查询商品信息
     * @param key
     * @param saleable
     * @param page
     * @param rows
     * @return
     */
    public PageResult<SpuBo> querySpuBoByPage(String key, Boolean saleable, Integer page, Integer rows) {

        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        //添加搜索条件
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("title","%" + key + "%");
        }

        //添加上下架状态
        if(saleable != null){
            criteria.andEqualTo("saleable",saleable);
        }

        //分页条件
        PageHelper.startPage(page,rows);

        //执行查询
        List<Spu> spus = this.spuMapper.selectByExample(example);
        PageInfo<Spu> pageInfo = new PageInfo<>(spus);

        //创建集合SpuBo
        List<SpuBo> spuBoList = new ArrayList<>();

        spus.forEach(spu -> {
            SpuBo spuBo = new SpuBo();

            //copy共同属性的值到新的集合
            BeanUtils.copyProperties(spu,spuBo);

            //查询品牌名称
            Brand brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
            spuBo.setBname(brand.getName());

            //查询分类名称
            List<String> name = this.categoryService.queryNameById(Arrays.asList(spu.getCid1(),
                    spu.getCid2(), spu.getCid3()));
            spuBo.setCname(StringUtils.join(name,"/"));

            spuBoList.add(spuBo);

        });

        //返回结果
        return new PageResult<>(pageInfo.getTotal(),spuBoList);
    }

    /**
     * 新增商品
     * @param spuBo
     */
    @Transactional
    public void insertGoods(SpuBo spuBo) {
        //新增spu
        //设置默认字段
        spuBo.setId(null);
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreteTime( new Date());
        spuBo.setLastUpdateTime(spuBo.getCreteTime());
        this.spuMapper.insertSelective(spuBo);

        // 新增spuDetail
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetail.setSpuId(spuBo.getId());
        this.spuDetailMapper.insertSelective(spuDetail);

        saveSkuAndStock(spuBo);

        sendMessage(spuBo.getId(),"insert");
    }

    private void saveSkuAndStock(SpuBo spuBo) {

        spuBo.getSkus().forEach(sku -> {
            // 新增sku
            sku.setSpuId(spuBo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insertSelective(sku);

            // 新增库存
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insertSelective(stock);
        });
    }

    /**
     * 根据spuId查询spuDetail
     * @param spuId
     * @return
     */
    public SpuDetail querySpuDetailBySpuId(Long spuId) {

        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }

    /**
     * 根据spuId查询Sku数据
     * @param spuId
     * @return
     */
    public List<Sku> querySkuBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skuList = this.skuMapper.select(sku);

        for (int i = 0; i < skuList.size(); i++) {
            Stock stock = this.stockMapper.selectByPrimaryKey(skuList.get(i).getId());
            sku.setStock(stock.getStock());
        }

        return skuList;
    }

    /**
     * 修改商品
     * @param spuBo
     */
    @Transactional
    public void updateGoods(SpuBo spuBo) {
        //查询以前sku
        List<Sku> skus = this.querySkuBySpuId(spuBo.getId());
        //如果以前不存在,则删除
        if(!CollectionUtils.isEmpty(skus)){
            List<Long> ids = skus.stream().map(s -> s.getId()).collect(Collectors.toList());
            // 删除以前库存
            Example example = new Example(Stock.class);
            example.createCriteria().andIn("skuId", ids);
            this.stockMapper.deleteByExample(example);

            // 删除以前的sku
            Sku record = new Sku();
            record.setSpuId(spuBo.getId());
            this.skuMapper.delete(record);
        }

        // 新增sku和库存
        saveSkuAndStock(spuBo);

        // 更新spu
        spuBo.setLastUpdateTime(new Date());
        spuBo.setCreteTime(null);
        spuBo.setValid(null);
        spuBo.setSaleable(null);
        this.spuMapper.updateByPrimaryKeySelective(spuBo);

        // 更新spu详情
        this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

        this.sendMessage(spuBo.getId(),"update");
    }

    /**
     * 删除商品
     * @param id
     */
    public void deleteGoods(Long id) {

        this.spuMapper.deleteByPrimaryKey(id);
        Sku sku = new Sku();
        sku.setSpuId(id);

        this.skuMapper.deleteByPrimaryKey(sku.getId());
        this.stockMapper.deleteByPrimaryKey(sku.getId());
    }

    /**
     * 下架商品
     * @param id
     */
    public void upGoods(Long id) {

        this.spuMapper.upGoods(id);
    }

    /**
     * 根据spuId查询spu
     * @param id
     * @return
     */
    public Spu querySpuById(Long id) {
        return this.spuMapper.selectByPrimaryKey(id);
    }

    private void sendMessage(Long id,String type){
        //发送消息
        try {
            this.amqpTemplate.convertAndSend("item." + type,id);
        }catch (Exception e){
            logger.error("{}商品消息发送异常，商品id：{}",type,id,e);
        }

    }

    public Sku getSkuBySkuId(Long skuId) {
        return this.skuMapper.selectByPrimaryKey(skuId);
    }
}
